#!/usr/bin/env python

# (c) 2007-2011 Helsinki University of Technology and University of Helsinki
# Licensed under the MIT license; see LICENSE.txt for more information.

from harava.rdf import *


class RDFTweaksImporter (RDFImporter):

  def modify(self, rdf, subj, pred, obj):
    if isinstance(pred, URIRef):
      # SAHA-specific metadata is unnecessary
      if pred.startswith(SAHA3): return None
      # SKOS and RDFS label information is unnecessary
      if pred.startswith(SKOS): return None
      if pred == RDFS.label: return None

    if subj.startswith(ICALOLD):
      subj = URIRef(subj.replace(ICALOLD, ICAL))
    if pred.startswith(ICALOLD):
      pred = URIRef(pred.replace(ICALOLD, ICAL))
    if obj.startswith(ICALOLD):
      obj = URIRef(obj.replace(ICALOLD, ICAL))

    if pred == DC.type and not obj.startswith(DCMITYPE):
      # invalid value for DC.type
      return None

    if pred == DC['format'] and isinstance(obj, URIRef) and not obj.startswith(IANAMIME):
      # custom MIME types - these are often broken
      # check if the object (instance) has an RDF.value
      
      val = rdf.value(obj, RDF.value, None)
      if not val: # broken
        # figure out what it should be
        label = rdf.value(obj, RDFS.label, None)
        obj = IANAMIME[label.lower().split('/')[-1]]	# hack...but should work for common cases

    # change old-style instances-with-rdf:value into new-style literals
    if pred in (DCTERMS.issued, DCTERMS.dateAccepted, DCTERMS.modified, DC['format'], DC.language):
      if not isinstance(obj, Literal):
        val = rdf.value(obj, RDF.value, None)
        if not val: # broken
          # figure out what it should be
          val = rdf.value(obj, RDFS.label, None) # hack...but should work
        datatype = rdf.value(obj, RDF.type, None)
        if datatype == DCTERMS.RFC3066:	# upgrade language spec
          datatype=DCTERMS.RFC4646
        obj = Literal(val, datatype=datatype)
    
    if pred == TS.value: pred = RDF.value
    
    if pred == TS.url and isinstance(obj, Literal):
      obj = URIRef(obj)
    
    if pred == DCTERMS['abstract']: pred = DC.description
    
    if pred == TS.genre and obj == GENRE.infopage:
      obj = GENRE.article
      
    return subj, pred, obj

